#ifndef __CONDITION_H__
#define __CONDITION_H__

#include "Mutex.h"

/* ------------------------------------------------------------------- */
class CCondition: public CMutex {
public:
    // initialize condition
    CCondition(void) :
        CMutex() {
        pthread_cond_init(&mCondition, NULL);
    }

    // TODO make sure condition is unlocked
    ~CCondition() {
        pthread_cond_destroy(&mCondition);
    }

    // sleep this thread, waiting for condition signal
    void Wait(void) {
        pthread_cond_wait(&mCondition, &mMutex);

    }

    // sleep this thread, waiting for condition signal,
    // but bound sleep time by the relative time inSeconds.
    void TimedWait(time_t inSeconds) {
        struct timespec absTimeout;
        absTimeout.tv_sec = time(NULL) + inSeconds;
        absTimeout.tv_nsec = 0;
        pthread_cond_timedwait(&mCondition, &mMutex, &absTimeout);

        // avoid some compiler warnings about unused args
        int secs;
        secs = inSeconds;

    }

    // send a condition signal to wake one thread waiting on condition
    // in Win32, this actually wakes up all threads, same as Broadcast
    // use PulseEvent to auto-reset the signal after waking all threads
    void Signal(void) {
        pthread_cond_signal(&mCondition);

    }

    // send a condition signal to wake all threads waiting on condition
    void Broadcast(void) {
        pthread_cond_broadcast(&mCondition);

    }

protected:
    pthread_cond_t mCondition;

}; // end class Condition

#endif // CONDITION_H
